package com.wealth.log.web.interceptor;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.wealth.log.entity.LogSys;
import com.wealth.log.service.ILogSysService;
import com.wealth.system.entity.User;
import com.wealth.system.service.ShiroUser;

import iaas.annotation.Log;
import iaas.network.IpUtil;

public class LogInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private ILogSysService  logSysService;
	
	/**
	 * 该方法在目标方法调用之前被调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		//判断Controller方法
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			Log log = method.getAnnotation(Log.class);
			if (log != null) {
				
				//记录日志
				LogSys logSys = new LogSys();
				String ip = IpUtil.getClientIP(request);
				logSys.setIp(ip);
				logSys.setCreateTime(new Date());
				logSys.setMethod(log.method());
				if(SecurityUtils.getSubject().isAuthenticated()){		//通过SHIRO获取登录用户名
					User user = ShiroUser.getInstance().getUser();
					logSys.setUsername(user.getUsername());
					logSys.setCorp(user.getCorp());
				}else{
					logSys.setUsername(request.getParameter("username"));
				}
				logSysService.save(logSys);
			}
		}	
		
		return true;
	}

}
